package com.garlic.face.jlf.utils;

import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Created by lyq on 2017/3/24.
 * Email: lyqcy1337@163.com
 * Version: v1.0
 * 日志文件本地操作工具类
 */

public class LogFileUtil {

    private static SimpleDateFormat logNameFormat = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
    private static SimpleDateFormat writeTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

    /**
     * 写入当天日志
     *
     * @return
     */
    public static boolean writeLog(String logInfo) {
        String logMsg = "[" + writeTimeFormat.format(new Date()) + "] " + logInfo + "\n";
        boolean ret = true;
        try {
            File file = new File(getFileDir());
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(file, true);
            fos.write(logMsg.getBytes("UTF-8"));
            fos.close();
        } catch (Exception e) {
            ret = false;
        }
        return ret;
    }

    /**
     * 返回日志文件路径，用于日志的写入
     *
     * @return
     */
    private static String getFileDir() {
        String logFileName = "";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // SD存在记录在SD卡上
            String sdFile = Environment.getExternalStorageDirectory().toString();
            StringBuilder sbLog = new StringBuilder();
            logFileName = sbLog.append(sdFile)
                    .append(File.separator)
                    .append("FacePayJLFLog")
                    .toString();
            File file = new File(logFileName);
            if (!file.exists()) {
                file.mkdirs();
            }
            logFileName = sbLog.append(File.separator)
                    .append(getFileMiddleName())
                    .append(".txt")
                    .toString();
        }
        return logFileName;
    }

    private static String getFileMiddleName() {
        return logNameFormat.format(new Date());
    }

}
